#include "Light.h"
#include <GL/gl.h>

namespace{
    int nextID=0;
    int lights[8]= {GL_LIGHT0, GL_LIGHT1, GL_LIGHT2, GL_LIGHT3, GL_LIGHT4, GL_LIGHT5, GL_LIGHT6, GL_LIGHT7};
}

Light::Light(const Point3f& pos, const Vector3f& diffuse, const Vector3f& specular) :
    position(pos), diffuse( diffuse ), specular ( specular ), m_name("Light")
{

    //position[0] = pos[0];
    //position[1] = pos[1];
    //position[2] = pos[2];

    //this->diffuse[0] = diffuse[0];
    //this->diffuse[1] = diffuse[1];
    //this->diffuse[2] = diffuse[2];
    //this->specular[0] = specular[0];
    //this->specular[1] = specular[1];
    //this->specular[2] = specular[2];
    ID = nextID;
    nextID++;
}

Light::~Light()
{
    glDisable(lights[ID]);
}

Point3f Light::getPosition()
{
    return position;
}

Vector3f Light::getDiffuse()
{
    return diffuse;
}

Vector3f Light::getSpecular()
{
    return specular;
}

void Light::setPosition(const Point3f &pos)
{
    position = pos;
}

void Light::setDiffuse(const Vector3f &diff)
{
    diffuse = diff;
}

void Light::setSpecular(const Vector3f &spec)
{
    specular = spec;
}

void Light::applyGL()
{
    // Desenha um ponto na posição da luz.
    glPushAttrib(GL_ALL_ATTRIB_BITS);
    glDisable(GL_LIGHTING);
    glDisable(GL_TEXTURE_2D);
    glPointSize(6);
    glColor3fv(&diffuse.x);
    glBegin(GL_POINTS);
        glVertex3fv(&position.x);
    glEnd();
    glPopAttrib();

    if(ID<8){
        glEnable(GL_LIGHTING);
        glEnable (lights[ID]);

        GLfloat dif[4]={diffuse.x,diffuse.y,diffuse.z,1};
        GLfloat spec[4]={specular.x,specular.y,specular.z,1};
        GLfloat pos[4]={position.x,position.y,position.z,1};

        glLightfv (lights[ID], GL_DIFFUSE, dif);//this->diffuse );
        glLightfv (lights[ID], GL_SPECULAR, spec);//this->specular );
        glLightfv (lights[ID], GL_POSITION, pos);//this->position);
    }
}

std::string Light::getName()
{
    return m_name;
}

void Light::setName(const std::string &name)
{
    m_name = name;
}
